#pragma once
#include <sys/epoll.h>
#include "Log.hpp"
#include "Common.hpp"

using namespace MyLogModule;


/**
 * 对epoll的封装
 */
 namespace EpollModule
 {
    const  int gdefault_epfd = -1;
    class Epoller
    {
    private:
        int _epfd;  //epoll模型的句柄

    public:
        Epoller()
            :_epfd(gdefault_epfd)
        {}

        void Init()
        {
            //创建epoll模型
            _epfd = epoll_create(2);
            if(_epfd < 0)
            {
                LOG(LogGrade::ERROR) << "epoll create fail" ;
                exit(EPOLL_CREATE_ERR);
            }
            LOG(LogGrade::ERROR) << "epoll create success" ;
        }

        int Wait(struct epoll_event event[],int maxnum,int timeout)
        {

            int n = epoll_wait(_epfd, event, maxnum, timeout);
            if(n < 0)
            {
                LOG(LogGrade::ERROR) << "epoll wait fail" ;
            }
            return n;
        }

        void Ctl(int fd,uint32_t event,int flag)
        {
            struct epoll_event ev;
            ev.data.fd = fd;
            ev.events = event;
            int n = epoll_ctl(_epfd, flag, fd, &ev);
            if(n < 0)
            {
                LOG(LogGrade::ERROR) << "epoll ctl fail" ;
                exit(EPOLL_CTRL_ERR);
            }
            LOG(LogGrade::ERROR) << "epoll ctl success" ;
        }

        void Add(int fd,uint32_t event)
        {
            Ctl(fd,event,EPOLL_CTL_ADD);
        }

        void Update(int fd,uint32_t event)
        {
            Ctl(fd,event,EPOLL_CTL_MOD);
        }

        void Del(int fd)
        {
            int n = epoll_ctl(_epfd,EPOLL_CTL_DEL,fd,nullptr);
            if(n < 0)
            {
                LOG(LogGrade::ERROR) << "epoll del fail";
            }
        }

        ~Epoller()
        {}
    };
 }